package com.appspot.mscheckers;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceException;


public final class EMF {
    private static final EntityManagerFactory emfInstance = Persistence.createEntityManagerFactory("transactions-optional");

    private EMF() {}

    public static EntityManagerFactory get() {
        return emfInstance;
    }
    
    /**
     * @param u : Object to be inserted
     * @return true if u inserted, false otherwise
     */
    public static boolean insert(Object u) {
 	   boolean result = true;
 	   EntityManager em = EMF.get().createEntityManager();
 	   try {
 		   em.getTransaction().begin();
 	       em.persist(u);
 	       em.getTransaction().commit();
 	   }catch(PersistenceException e){
 		   System.out.println("Dao insert : "+e);
 		   e.printStackTrace();
 		   result = false;  
 	   }
 	   finally{ em.close(); }
 	return result;
 	}
    

    public static boolean update(Object u) {
 	   boolean result = true;
 	   EntityManager em = EMF.get().createEntityManager();
 	   try {
 		   em.getTransaction().begin();
 	       em.merge(u);
 	       em.getTransaction().commit();
 	   }catch(PersistenceException e){
 		   System.out.println("Dao insert : "+e);
 		   e.printStackTrace();
 		   result = false;  
 	   }
 	   finally{ em.close(); }
 	return result;
 	}
    
    /**
     * Find user by Id
     * @param id : user id
     * @return user if id exist, null otherwise
     */
    public static User getUser(String id){
 	   User u;
 	   EntityManager em = EMF.get().createEntityManager();
 	   try{
 		   
 		  u = em.find(User.class, id);

 	   }catch(PersistenceException e){ u = null;} 
 	   finally{ em.close(); }
    return u;
    }
}